package com.nikkerball.web.converter;

import com.nikkerball.converter.Conversion;
import com.nikkerball.unit.EnergyUnit;
import com.nikkerball.unit.Unit;
import com.nikkerball.web.base.BasePanel;
import com.nikkerball.web.renderers.ChoiceRenderer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;

import java.math.BigDecimal;
import java.util.Arrays;

/**
 * User: Marius
 * Date: 14-Feb-2010
 * Time: 18:14:00
 */
public class EnergyConverterPanel extends BasePanel {

    @SuppressWarnings({"UnusedDeclaration"})
    private BigDecimal fromAmount;

    @SuppressWarnings({"UnusedDeclaration"})
    private Unit fromUnit;

    @SuppressWarnings({"UnusedDeclaration"})
    private Unit toUnit;

    private ComputationsPanel computationsPanel;

    public EnergyConverterPanel(String id, ComputationsPanel computationsPanel) {
        super(id);
        this.computationsPanel = computationsPanel;

        Form converterForm = new Form("converterForm");

        TextField<Double> fromAmountTextField = new TextField<Double>("fromAmountTextField",
                new PropertyModel<Double>(this, "fromAmount"));
        DropDownChoice<Unit> fromUnitDropDownChoice = new DropDownChoice<Unit>("fromUnitDropDownChoice",
                new PropertyModel<Unit>(this, "fromUnit"), Arrays.asList(EnergyUnit.values()),
                new ChoiceRenderer(this));
        DropDownChoice<Unit> toUnitDropDownChoice = new DropDownChoice<Unit>("toUnitDropDownChoice",
                new PropertyModel<Unit>(this, "toUnit"), Arrays.asList(EnergyUnit.values()), new ChoiceRenderer(this));

        fromAmountTextField.setRequired(true);
        fromUnitDropDownChoice.setRequired(true);
        toUnitDropDownChoice.setRequired(true);

        AjaxButton convertButton = new AjaxButton("convertButton") {
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                Conversion conversion = new Conversion(fromUnit, toUnit, fromAmount);
                EnergyConverterPanel.this.computationsPanel.getComputations().add(conversion);
                target.addComponent(EnergyConverterPanel.this.computationsPanel);
            }
        };

        converterForm.add(fromAmountTextField);
        converterForm.add(fromUnitDropDownChoice);
        converterForm.add(toUnitDropDownChoice);
        converterForm.add(convertButton);

        add(converterForm);
    }
}
